/**
 * Copyright (C) 2008+ Spark Zheng
 *
 * @file test/test_josephus.c 
 * @date 2009-11-12
 * @brief
 * @see  dlib/test
 * @history
 */

#include <stdio.h>
#include <stdlib.h>
#include <stdint.h>
#include <string.h>

#include "list.h"

typedef struct data_head {
	list_node_t	head;
	uint32_t	num;
} S_HEAD;

typedef struct data_node {
	list_node_t	ln;
	uint32_t	data;
} S_NODE;


int main(int argc, char *argv[])
{
	int i;
	int count = 1;
	int N = 10;
	int M = 3;

	if (argc > 2)
		N = (int)atoi(argv[1]);
	if (argc > 3)
		M = (int)atoi(argv[2]);

	S_HEAD l_head;

	LIST_HEAD_INIT(&l_head.head);
	l_head.num = 0;

	S_NODE l_node[N];

	list_node_t *pos = NULL;
	list_node_t *tmp = NULL;
	
	for (i = 1; i <= N; i++) {
		l_node[i - 1].data = i;
		LIST_ADD_TAIL(&l_head.head, &l_node[i - 1].ln);
		l_head.num++;
	}

	pos = LIST_FIRST(&l_head.head);
	while(count <= N * M) {
		if (count % M == 0) {
			printf("get %dth element: %d\n", count / M,\
				LIST_ENTRY(pos, S_NODE, ln)->data);
			tmp = pos;
			pos = pos->next;
			LIST_DEL(tmp);
		} else {
			pos = pos->next;
		}
		 
		if (pos == &l_head.head) {
			pos = LIST_FIRST(&l_head.head);
		}
		count++; 
	}

	return 0;
}
